import configparser
import os

from .database_ui import *
from PyQt5.QtWidgets import QWidget, QTableWidgetItem


class UIDataBaseView(QWidget, Ui_MySQL):
    def __init__(self):
        super(UIDataBaseView, self).__init__()
        self.setupUi(self)
        self.initParams()
        self.initUI()
        self.initSlot()
        self.initMethod()
        self.initAction()

    def initUI(self):
        pass

    def initSlot(self):
        self.submit_PB.clicked.connect(self.submit)

    def initMethod(self):
        pass

    def initAction(self):
        self.submitCallback = None

    def initParams(self):
        if os.path.isfile(os.path.dirname(os.path.realpath(__file__)) + '/database.ini'):
            conf = configparser.ConfigParser()
            conf.read(os.path.dirname(os.path.realpath(__file__)) + '/database.ini', encoding="utf-8")
            mysql_items = {}
            for item in conf.items("mysql"):
                mysql_items[item[0]] = item[1]
            self.host_LE.setText(mysql_items['host'])
            self.database_LE.setText(mysql_items['db'])
            self.username_LE.setText(mysql_items['user'])
            self.password_LE.setText(mysql_items['password'])
            self.port_LE.setText(mysql_items['port'])
            self.charset_LE.setText(mysql_items['charset'])
            self.prefix_LE.setText(mysql_items['prefix'])
            self.datetime_format_LE.setText(mysql_items['datetime_format'])
        else:
            with open(os.path.dirname(os.path.realpath(__file__)) + '/database.ini', 'w+') as fp:
                fp.write(
                    "[mysql]\nhost = \ndb = \nuser = \npassword = \nport = \ncharset = \nprefix = \ndatetime_format = \n")

    def submit(self):
        conf = configparser.ConfigParser()
        conf.read(os.path.dirname(os.path.realpath(__file__)) + '/database.ini', encoding="utf-8")
        conf.set('mysql', 'host', self.host_LE.text())
        conf.set('mysql', 'db', self.database_LE.text())
        conf.set('mysql', 'user', self.username_LE.text())
        conf.set('mysql', 'password', self.password_LE.text())
        conf.set('mysql', 'port', self.port_LE.text())
        conf.set('mysql', 'charset', self.charset_LE.text())
        conf.set('mysql', 'prefix', self.prefix_LE.text())
        conf.set('mysql', 'datetime_format', self.datetime_format_LE.text())
        conf.write(open(os.path.dirname(os.path.realpath(__file__)) + '/database.ini', "w+", encoding="utf-8"))
        self.hide()
        if self.submitCallback: self.submitCallback()


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    ui = UIDataBaseView()
    ui.show()
    os._exit(app.exec_())